package com.itmake.sample.mqtt.producer;

import com.itmake.sample.mqtt.config.MqttConfig;
import com.itmake.sample.mqtt.constant.MqttConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import javax.annotation.Resource;

/**
 * MQTT生产者配置
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Configuration
@IntegrationComponentScan
public class MqttProducerConfig {

	@Resource
	private MqttConfig mqttConfig;

	@Resource
	private MqttPahoClientFactory mqttClientFactory;

	/**
	 * 信息通道
	 *
	 * @return {@link MessageChannel}
	 */
	@Bean(name = MqttConstant.OUT_BOUND_CHANNEL)
	public MessageChannel mqttOutBoundChannel() {
		return new DirectChannel();
	}

	/**
	 * 消息处理器
	 *
	 * @return {@link MessageHandler}
	 */
	@Bean
    @ServiceActivator(inputChannel = MqttConstant.OUT_BOUND_CHANNEL)
    public MessageHandler mqttOutBound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
        		mqttConfig.getClientOutId(), mqttClientFactory);
        messageHandler.setAsync(true);
        // 解决“客户端订阅某一个主题时，会收到之前推送客户端发送的消息”的问题
		messageHandler.setDefaultRetained(false);
        return messageHandler;
    }
}
